<template>
  <div class="app-container">
    <my-tree-selector-query
      title="所属区域"
      :current-node-key="this.queryParams.regionId"
      :default-expanded-keys="[this.queryParams.regionId]"
      :options="regionDataOptions"
      :treeProps="{ children: 'children',label: 'name'}"
      @click-node="handleNodeClick"
    />
    <div class="right-wrap">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" @submit.native.prevent>
        <el-form-item label="分组名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入分组名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['device:group:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['device:group:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['device:group:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['device:group:export']"
          >导出
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="groupList"
        @selection-change="handleSelectionChange"
        row-key="id"
        lazy
        :load="load"
        ref="table"
        :key="forceUpdateKey"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="名称" align="left" prop="name"/>
        <el-table-column label="分组ID" align="center" prop="id"/>
        <!--   <el-table-column label="所属区域ID" align="center" prop="regionId"/>-->
        <el-table-column label="所属区域" align="center" prop="regionAncestorsName">
          <template slot-scope="scope">
            {{ scope.row.regionAncestorsName.replace(',', '') }}
          </template>
        </el-table-column>
        <el-table-column label="父级ID" align="center" prop="parentId"/>
        <el-table-column label="分组祖级列表" align="center" prop="ancestors"/>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['device:group:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['device:group:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        layout="sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 添加或修改分组管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" ref="editDialog" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="所属区域" prop="regionId">
          <el-cascader
            style="width: 100%;"
            filterable
            clearable
            v-model="form.regionId"
            ref="cascader"
            placeholder="请选择设备部署区域"
            :props="elCascaderProps"
            :options="pageRegionDataOptions"
          />
        </el-form-item>

        <el-form-item label="所属父级" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :options="copyAllGroupOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择分组所属父级"
            noOptionsText="暂无选项"
            noResultsText="没有匹配的搜索结果"
          />
        </el-form-item>

        <el-form-item label="分组名称" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入分组名称"/>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listGroup, getGroup, delGroup, addGroup, updateGroup, getChildGroup} from "@/api/device/group";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import MyTreeSelectorQuery from "@/views/components/myTreeSelectorQuery";

export default {
  name: "Group",
  components: {Treeselect, MyTreeSelectorQuery},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分组管理表格数据
      groupList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        parentId: 0,
        regionId: undefined
      },
      // 表单参数
      form: {},
      oldParentId: undefined,
      // 表单校验
      rules: {
        regionId: [
          {required: true, message: "所属区域不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "分组名称不能为空", trigger: "blur"}
        ],
        parentId: [
          {required: true, message: "所属父级不能为空", trigger: "blur"}
        ],
      },
      //table的key 获取数据时重新渲染表格，解决删除修改懒加载的子节点时刷新有缓存问题
      forceUpdateKey: Math.random(),
      // 页面区域选项数据，区域联动选择器和树形选项选择器根据这个数据渲染
      pageRegionDataOptions: [],
      // 区域级联选择器配置
      elCascaderProps: {
        value: 'id',
        label: 'name',
        lazy: true,
        lazyLoad() {
        },
        emitPath: false,
        checkStrictly: true,
        expandTrigger: 'hover'
      }
    };
  },
  computed: {
    //默认显示省份ID
    provinceIdConfig() {
      return this.$store.state.app.provinceIdConfig
    },
    // 分组数据
    groupOptions() {
      return this.$store.state.device.groupOptions || []
    },
    // 复制一份分组数据，最外层加个无父分组选项
    copyAllGroupOptions() {
      return [{
        children: this.groupOptions,
        code: -1,
        id: 0,
        name: '无',
      }]
    },
    // 所有地区树形数据
    regionDataOptions() {
      return this.$store.state.device.regionDataOptions || []
    },
  },
  watch: {
    regionDataOptions: {
      handler(newValue) {
        this.pageRegionDataOptions = newValue.map(item => {
          return {
            ...item,
            children: item.children ? null : undefined,
            leaf: item.children ? false : true,
          }
        })
      },
      immediate: true
    }
  },
  created() {
    // 区域联动级联选择器懒加载方法设置
    this.elCascaderProps.lazyLoad = ((node, resolve) => {
      // 如果不是第一级区域或者已经存在子区域了，表示已有子节点不需要重新加载，直接resolve()
      if (node.level !== 1 || node.children.length) return resolve();
      node.data.children = this.regionDataOptions.find(item => {
        return item.id === node.value
      }).children;
      resolve();
    })
    // 默认选中和展开设置的省节点
    this.queryParams.regionId = this.provinceIdConfig;

    this.getList();
  },
  mounted() {
    /*在页面渲染完后调用dialog实例，将rendered置为true，提前渲染dialog里面内容，
    解决第一次打开弹窗时，由于里面级联选择器数据过多，渲染导致的延迟问题*/
    this.$refs.editDialog.rendered = true;
  },
  methods: {
    handleNodeClick(data) {
      this.queryParams.regionId = data.id;
      this.handleQuery();
    },
    /** 转换区域树形图数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    // 点击table下拉加载下属区域
    load(tree, treeNode, resolve) {
      const id = tree.id;

      getChildGroup({id}).then(res => {
        const list = res.rows.map(item => {
          // haveChildren是1的话表示还有下一级
          // console.log("id", {hasChildren: item.haveChildren === '1', ...item})
          return {hasChildren: item.haveChildren === '1', ...item,}
        });

        // 遍历子的数据是否已存在外部表格，如果存在则去掉，解决搜索后展开会有相同项问题
        list.forEach(item =>{
          const index =  this.groupList.findIndex(childItem => item.id === childItem.id)
          if(index >= 0){
            this.groupList.splice(index, 1)
          }
        })

        resolve(list)
        // console.log("groupList===》",this.groupList)

      })
    },
    /** 查询分组管理列表 */
    getList() {
      this.loading = true;
      listGroup(this.queryParams).then(response => {
        const list = response.rows.map(item => {
          // haveChildren等于'1'表示还有下一级
          return {hasChildren: item.haveChildren === '1', ...item}
        });
        this.forceUpdateKey = Math.random();
        this.groupList = list;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        status: 0,
        remark: null,
        parentId: null,
        ancestors: null,
        regionId: null,
        regionAncestors: null,
        regionAncestorsName: null
      };
      this.oldParentId = undefined;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加分组管理";
    },

    // 区域选项加载下面子区域
    loadRegionOptions({parentNode, callback}) {
      if (!parentNode) return callback && callback();
      if (parentNode.children && parentNode.children.length) return callback && callback();
      parentNode.children = this.regionDataOptions.find(item => {
        return item.id === parentNode.id
      }).children;
      callback && callback();
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGroup(id).then(response => {

        const oldForm = response.data;
        /*把ancestors字符串转为数组,因为在添加的时候统一给ancestors加了父级id0，并且去掉了自身id
          在更新的时候要将最第一级0去掉,在最后面加上自身id */
        oldForm.regionAncestors = oldForm.regionAncestors.split(",").slice(1);
        oldForm.regionAncestors.push(oldForm.regionId);
        const parentNode = this.pageRegionDataOptions.find(item => {
          return item.id === oldForm.regionAncestors[0]
        })
        // 如果该省份不存在子区域数据并且不是最后一级，需要提前添加数据渲染，才能让修改时自动选中区域
        if (parentNode && (!parentNode.children && !parentNode.leaf)) {
          this.loadRegionOptions({parentNode})
        }

        this.form = oldForm;
        this.oldParentId = oldForm.parentId;

        this.open = true;
        this.title = "修改分组管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const checkedNodes = this.$refs.cascader.getCheckedNodes()[0];
          // 前面加上0，裁切掉最后一个
          const ancestors = [0, ...checkedNodes.path.slice(0, -1)].join(",");
          const regionLabel = checkedNodes.pathLabels.join(",");
          // 将选中部署区域的祖级id前面统一加0，方便后端查询

          const params = {
            name: this.form.name,
            parentId: this.form.parentId,
            id: this.form.id,
            remark: this.form.remark,
            regionId: this.form.regionId,
            regionAncestors: ancestors,
            regionAncestorsName: regionLabel,
          };

          // console.log("请求参数", params);

          if (this.form.id != null) {
            if(this.form.id === this.form.parentId) {
              return  this.$modal.confirmAlert('不允许选自己作为父级分组！')
            }
            updateGroup({
              ...params,
              oldParentId: this.oldParentId
            }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList()
              // 更新分组数据保存到vuex
              this.$store.dispatch('LoadGroupOptionsTree');
            });
          } else {
            addGroup(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 更新分组数据保存到vuex
              this.$store.dispatch('LoadGroupOptionsTree');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除分组管理编号为"' + ids + '"的数据项？').then(function () {
        return delGroup(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        // 更新分组数据保存到vuex
        this.$store.dispatch('LoadGroupOptionsTree');
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      this.download('device/group/export', {
        ...this.queryParams
      }, `分组管理_${currentDate}.xlsx`)
    }
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  display: flex;
  min-height: inherit;

  .right-wrap {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }
}
</style>
